/**
 * @Title wheel-utils系统
 * @Package com.senyint.sys.utils.ws
 * @Description TODO
 * @Company 心医国际数字医疗系统（大连） 有限公司
 * @Copyright (c) 2016, 2017, Senyint. All rights reserved.
 * @date 2018年3月5日 下午3:09:47 
 * @author WangNaiFei
 * @version 1.0
 */

package com.senyint.sys.utils.ws;

import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;

import com.senyint.sys.utils.log.Log;

/**
 * {@code WebServiceUtils}
 * 
 * @Description: TODO
 *               <p>
 * @author WangNaiFei,WangNaiFei@senyint.com
 * @date 2018年3月5日 下午3:09:06
 * @version 1.0
 * @since jdk1.7+
 */
public class WebServiceUtils {

	/**
	 * @Title: callWebService
	 * @Description: TODO
	 * @author WangNaiFei,WangNaiFei@senyint.com
	 * @date 2018年3月20日 下午7:51:24
	 * @version 1.0
	 * @param url
	 * @param methodName
	 * @param connectionTimeout 连接超时 单位毫秒
	 * @param receiveTimeout 响应超时 单位毫秒
	 * @param args
	 * @return
	 * @throws Exception
	 */
	public static Object[] callWebService(String url, String methodName, Long connectionTimeout, Long receiveTimeout, Object... args) throws Exception {
		if (connectionTimeout == null) {
			connectionTimeout = 3000l;
		}
		Log.INSTANCE.debug("webservice connectionTimeout:{}", connectionTimeout);

		if (receiveTimeout == null) {
			receiveTimeout = 3000l;
		}
		Log.INSTANCE.debug("webservice receiveTimeout:{}", receiveTimeout);

		Log.INSTANCE.debug("webservice url:{}", url);
		Log.INSTANCE.debug("webservice methodName:{}", methodName);
		Log.INSTANCE.debug("webservice args:{}", args);

		JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
		Client client = dcf.createClient(url);
		HTTPConduit http = (HTTPConduit) client.getConduit();
		HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
		httpClientPolicy.setConnectionTimeout(connectionTimeout);
		httpClientPolicy.setAllowChunking(false); // 取消块编码
		httpClientPolicy.setReceiveTimeout(receiveTimeout);
		http.setClient(httpClientPolicy);
		//
		// String addr = url.replace("?wsdl", "");
		// Log.INSTANCE.debug("webservice http address:{}", addr);
		// http.getTarget().getAddress().setValue(addr);
		Log.INSTANCE.debug("webservice client invoke");
		Object[] object = client.invoke(methodName, args);
		Log.INSTANCE.debug("webservice return {} result size", object == null ? 0 : object.length);
		return object;
	}

}